import mysql from 'mysql2/promise'
import { config } from 'dotenv'

config()

const target = process.env.TARGET

export const pool = mysql.createPool({
  host: target === 'dev' ? process.env.DEV_DB_HOST : process.env.DB_HOST,
  port: Number(process.env.DB_PORT),
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  waitForConnections: true,
  connectionLimit: 10
})

export const query = async (sql: string, values?: any[]) => {
  const connection = await pool.getConnection()
  try {
    const [rows] = await connection.execute(sql, values)
    return rows
  } finally {
    connection.release()
  }
}
